import { ElMessage, ElMessageBox } from 'element-plus'
import { preventDuplicateSubmit } from './preventDuplicateSubmit'

/**
 * 表单处理工具函数
 */

/**
 * 处理表单提交的通用函数
 * @param formRef 表单引用
 * @param submitFn 提交函数
 * @param options 配置选项
 */
export async function handleSubmit<T>(
  formRef: any,
  submitFn: () => Promise<T>,
  options: {
    successMessage?: string
    errorMessage?: string
    successCallback?: () => void
    errorCallback?: (error: any) => void
  } = {}
) {
  if (!formRef) return

  const {
    successMessage = '操作成功',
    errorMessage = '操作失败',
    successCallback,
    errorCallback
  } = options

  try {
    await formRef.validate()
    const result = await submitFn()
    ElMessage.success(successMessage)
    successCallback?.()
    return result
  } catch (error: any) {
    ElMessage.error(errorMessage)
    errorCallback?.(error)
    throw error
  }
}

/**
 * 处理删除确认的通用函数
 * @param itemName 项目名称
 * @param deleteFn 删除函数
 * @param options 配置选项
 */
export async function handleDeleteConfirm(
  itemName: string,
  deleteFn: () => Promise<void>,
  options: {
    title?: string
    confirmMessage?: string
    successMessage?: string
    errorMessage?: string
  } = {}
) {
  const {
    title = '确认删除',
    confirmMessage = `确定要删除${itemName}吗？`,
    successMessage = '删除成功',
    errorMessage = '删除失败'
  } = options

  try {
    await ElMessageBox.confirm(confirmMessage, title, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteFn()
    ElMessage.success(successMessage)
    return true
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(errorMessage)
    }
    return false
  }
}

/**
 * 批量删除确认的通用函数
 * @param count 项目数量
 * @param itemType 项目类型
 * @param deleteFn 删除函数
 * @param options 配置选项
 */
export async function handleBatchDeleteConfirm(
  count: number,
  itemType: string,
  deleteFn: () => Promise<void>,
  options: {
    title?: string
    confirmMessage?: string
    successMessage?: string
    errorMessage?: string
  } = {}
) {
  const {
    title = '确认删除',
    confirmMessage = `确定要删除选中的 ${count} 个${itemType}吗？`,
    successMessage = '删除成功',
    errorMessage = '删除失败'
  } = options

  return handleDeleteConfirm('', deleteFn, {
    title,
    confirmMessage,
    successMessage,
    errorMessage
  })
}

/**
 * 重置表单的通用函数
 * @param formRef 表单引用
 * @param formData 表单数据对象
 * @param defaultValues 默认值
 */
export function resetForm(formRef: any, formData: any, defaultValues: Record<string, any> = {}) {
  if (formRef) {
    formRef.resetFields()
  }

  // 重置表单数据
  Object.keys(defaultValues).forEach(key => {
    formData[key] = defaultValues[key]
  })
}

/**
 * 处理API错误的通用函数
 * @param error 错误对象
 * @param customMessage 自定义错误消息
 */
export function handleApiError(error: any, customMessage?: string) {
  console.error('API Error:', error)

  let message = customMessage || '请求失败，请稍后重试'

  if (error.response) {
    const { status, data } = error.response
    switch (status) {
      case 400:
        message = data.message || '请求参数错误'
        break
      case 401:
        message = '未授权，请重新登录'
        break
      case 403:
        message = '拒绝访问'
        break
      case 404:
        message = '请求的资源不存在'
        break
      case 500:
        message = '服务器内部错误'
        break
      default:
        message = data.message || `请求失败 (${status})`
    }
  } else if (error.request) {
    message = '网络连接失败，请检查网络设置'
  } else {
    message = error.message || message
  }

  ElMessage.error(message)
  return Promise.reject(error)
}

/**
 * 处理创建/更新操作的通用函数
 * @param isEdit 是否为编辑模式
 * @param createFn 创建函数
 * @param updateFn 更新函数
 * @param options 配置选项
 */
export async function handleCreateUpdate<T>(
  isEdit: boolean,
  createFn: () => Promise<T>,
  updateFn: () => Promise<T>,
  options: {
    createSuccessMessage?: string
    updateSuccessMessage?: string
    createErrorMessage?: string
    updateErrorMessage?: string
    successCallback?: () => void
    errorCallback?: (error: any) => void
  } = {}
) {
  const {
    createSuccessMessage = '创建成功',
    updateSuccessMessage = '更新成功',
    createErrorMessage = '创建失败',
    updateErrorMessage = '更新失败',
    successCallback,
    errorCallback
  } = options

  try {
    const result = isEdit ? await updateFn() : await createFn()
    ElMessage.success(isEdit ? updateSuccessMessage : createSuccessMessage)
    successCallback?.()
    return result
  } catch (error: any) {
    ElMessage.error(isEdit ? updateErrorMessage : createErrorMessage)
    errorCallback?.(error)
    throw error
  }
}

/**
 * 处理表单保存操作的通用函数（包含防重复提交）
 * @param submitKey 提交键
 * @param formRef 表单引用
 * @param saveFn 保存函数
 * @param options 配置选项
 */
export async function handleFormSave<T>(
  submitKey: string,
  formRef: any,
  saveFn: () => Promise<T>,
  options: {
    successMessage?: string
    errorMessage?: string
    successCallback?: () => void
    errorCallback?: (error: any) => void
  } = {}
) {
  const {
    successMessage = '保存成功',
    errorMessage = '保存失败',
    successCallback,
    errorCallback
  } = options

  try {
    await preventDuplicateSubmit(submitKey, async () => {
      try {
        await handleSubmit(formRef, saveFn, {
          successMessage,
          errorMessage,
          successCallback,
          errorCallback
        })
      } catch (error: any) {
        throw error // 重新抛出错误以确保防重复提交正确处理
      }
    })
  } catch (error: any) {
    // 防重复提交保护捕获的错误
    if (error.message === '请勿重复提交') {
      ElMessage.warning('请勿重复提交')
    }
  }
}

export default {
  handleSubmit,
  handleDeleteConfirm,
  handleBatchDeleteConfirm,
  resetForm,
  handleApiError,
  handleCreateUpdate,
  handleFormSave
}
